import axios from "axios";
const { VITE_BASE_URL } = import.meta.env; //导入环境变量
import { ElMessage } from "element-plus";
import Router from "../router/index";
const service = axios.create({
  baseURL: VITE_BASE_URL,
  timeout: 5000,
}) ;

//请求拦截器
service.interceptors.request.use(
  (config) => {
    //设置请求头sessionID

    //从localstorage获取sessionID
    const sessionId = localStorage.getItem("sessionId");
    if (sessionId) {
      config.headers["Zd-Session-Id"] = sessionId;
    }
    return config;
  },
  (err) => {
    return Promise.resolve(err);
  }
);
//响应拦截器
service.interceptors.response.use(
  (res) => {

    const data = res.data;
    if (data.code == 401) {
      //登录过期，跳回登录页
      ElMessage.warning("登录会话过期，请重新登录");
      localStorage.clear()
      Router.replace({ name: "Login" });
    }
    return data;
  },
  (err) => {
    ElMessage.error("请检查服务端");
    return Promise.resolve(err);
  }
);
export default service ;



